package directive;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modele.beans.Building;
import modele.dao.BuildingDAO;
import modele.form.BuildingForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class BuildingAction extends GlobalAction {

private BuildingDAO buildingDAO;
	
	@Override
	public String executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		buildingDAO = new BuildingDAO(this.conn);
		String type = (String) request.getParameter("type");
		String ac = ACTION_FAIL;

		if (type.equals("Ajouter"))
			ac = AddBuilding(mapping, form);
		else if (type.equals("Modifier"))
			ac = UpdateBuilding(mapping, form);
		else if (type.equals("Supprimer"))
			ac = DeleteBuilding(mapping, form);
		else
			ac = ACTION_SUCCESS;
		
		BuildingForm building = (BuildingForm) form;
		
		if (ac.equals(ACTION_SUCCESS)) {
			building.setName("");
			building.setAddress("");
			building.setPhoneNumber("");
			building.setId("");
		}
	
		building.setBuildings(GetBuildings());
		request.setAttribute("BuildingForm", building);
		
		return ac;
	}

	private String AddBuilding(ActionMapping mapping, ActionForm form) {
		BuildingForm building = (BuildingForm) form;

		Building b = new Building(building.getName(),
				building.getAddress(),
				building.getPhoneNumber(),
				building.getId());
		try {
			buildingDAO.AddBuilding(b);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}
	
	private String UpdateBuilding(ActionMapping mapping, ActionForm form) {
		BuildingForm building = (BuildingForm) form;

		Building b = new Building(building.getName(),
				building.getAddress(),
				building.getPhoneNumber(),
				building.getId());
		try {
			buildingDAO.UpdateBuilding(b);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}
	
	private String DeleteBuilding(ActionMapping mapping, ActionForm form) {
		BuildingForm building = (BuildingForm) form;

		Building b = new Building(building.getName(),
				building.getAddress(),
				building.getPhoneNumber(),
				building.getId());
		try {
			buildingDAO.RemoveBuilding(b);
		} catch (SQLException e) {
			return ACTION_FAIL;
		} catch (ClassNotFoundException e) {
			return ACTION_FAIL;
		}
		return ACTION_SUCCESS;
	}

	private ArrayList<Building> GetBuildings() {
		try {
			return buildingDAO.GetBuildings();
		} catch (SQLException e) {
			return new ArrayList<Building>();
		} catch (ClassNotFoundException e) {
			return new ArrayList<Building>();
		}
	}
}